﻿#include "mainwindow.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    logger->info("程序启动");





    try
    {

        QString m_model_dir = QCoreApplication::applicationDirPath() + "/function";
        HDevEngine().SetProcedurePath(m_model_dir.toLocal8Bit().toStdString().c_str());
    }
    catch (HDevEngineCpp::HDevEngineException &exception)
    {



        QMessageBox::information(nullptr, "", exception.Message());
    }
    bool ret =loadPara();
    if(ret == false)
    {
        //QMessageBox::critical(nullptr, "para", "参数文件不存在");
        qApp->quit();
    }

	QString qstring_path = m_type_dir + "/" + m_type_name + "/para.db";

	initQSQLITE(qstring_path);

    initMainWindow();

////    //*/存图线程开始
    m_save_image_thread = new SaveImageThread();
    m_save_image_thread->start();

    //检测类初始化
    {
        m_qdialog_detection = new QDialog(this);
        m_qdialog_detection->setModal(true);
        m_tabwidget_detection = new QTabWidget(m_qdialog_detection);
        m_tabwidget_detection->move(0, 0);
        m_tabwidget_detection->setFixedSize(1920, 1000);
        for (int i = 0; i < m_camera_number; i++)
        {
            QtThreadProcess* pQtThreadProcess = new QtThreadProcess();
            pQtThreadProcess->m_camera_index = i;
            QString section = "camera" + QString::number(i) + "/";
            pQtThreadProcess->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();
//            pQtThreadProcess->m_detection_number = m_settings_para->value(section + "m_detection_number", 1).toInt();
//            pQtThreadProcess->m_image_dir = m_settings_para->value(section + "m_image_dir", "").toString();
//            pQtThreadProcess->m_image_dir = m_exe_directory + "/images/camera" + QString::number(i);

            pQtThreadProcess->m_show_ratio = m_settings_para->value("para/m_show_ratio", "").toInt();
            pQtThreadProcess->m_delaye_number = m_settings_para->value(section + "m_delaye_number", 0).toInt();

            pQtThreadProcess->m_io_camera = m_settings_para->value(section + "m_io_camera", "").toInt();
            pQtThreadProcess->m_io_finish = m_settings_para->value(section + "m_io_finish", "").toInt();
            pQtThreadProcess->m_io_result = m_settings_para->value(section + "m_io_result", "").toInt();

            connect(pQtThreadProcess, &QtThreadProcess::sendDetectionResult, this, &MainWindow::showResult, Qt::QueuedConnection);
//            connect(pQtThreadProcess, &QtThreadProcess::sendComResult, this, &MainWindow::comResult, Qt::QueuedConnection);
//            connect(pQtThreadProcess, &QtThreadProcess::sendCameraFinish, this, &MainWindow::cameraFinish, Qt::QueuedConnection);
//            connect(pQtThreadProcess, &QtThreadProcess::sendCom, this, &MainWindow::sendCom, Qt::QueuedConnection);
            QString qstring_path = m_type_dir + "/" + m_type_name  +"/" + "camera" + QString::number(i) + ".ini";
            pQtThreadProcess->m_function = new Function(nullptr, qstring_path, i);
            connect(pQtThreadProcess->m_function->m_pushbutton_return, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            m_tabwidget_detection->addTab(pQtThreadProcess->m_function, pQtThreadProcess->m_camera_name);

//            pQtThreadProcess->start();
            m_vector_detection_thread.push_back(pQtThreadProcess);
        }
    }

    //dl_3初始化////////////////////////////////////
    dl_3_init();

    //相机类初始化
    {
        m_qdialog_camera = new QDialog(this);
        m_qdialog_camera->setModal(true);
        m_tabwidget_camera = new QTabWidget(m_qdialog_camera);
        m_tabwidget_camera->move(0, 0);
        m_tabwidget_camera->setFixedSize(1920, 1000);

		m_vector_show_image.resize(m_camera_number);

        for (int i = 0; i < m_camera_number; i++)
        {
			
            CameraBaseQDialog* p = new CameraBaseQDialog(nullptr, m_settings_para, "camera" + QString::number(i));
            connect(p->m_qpushbutton_hide, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            QString section = "camera" + QString::number(i) + "/";
            p->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();
            p->m_camera_index = i;


            m_tabwidget_camera->addTab(p, p->m_camera_name);
            if (m_online == 1)
            {
                //在线检测
                logger->info("camera connect");
                p->m_SN = m_settings_para->value(section + "m_SN", QString::number(i)).toString();
                p->m_type = m_settings_para->value(section + "m_type", QString::number(i)).toString();

                bool result = p->initCamera(p->m_type, p->m_SN, callback, m_vector_detection_thread[i]);
                if (result == false)
                {
                    QString StringMessage = QString("相机%1连接失败"+p->m_SN).arg(i);
                    QImage image(300,300,QImage::Format_RGB888);
                    image.fill(QColor(Qt::black));
                    m_vector_show_qlabel[i]->loadtextimage(image,StringMessage,QColor(Qt::red));
//                    //QMessageBox::information(nullptr, "相机错误", StringMessage);
                }



            }
            if (m_online == 0)
            {
                //离线检测
                p->m_image_dir = m_exe_directory + "/images/camera" + QString::number(i);
//                p->m_image_dir = m_settings_para->value(section + "m_image_dir", QString::number(i)).toString();
                QDir dir(p->m_image_dir);
                if (!dir.exists())
                {
                    //QMessageBox::critical(nullptr, "Title", "离线测试文件夹不存在");
                }
                else
                {
                    dir.setFilter(QDir::Files | QDir::NoSymLinks);
                    QStringList filters;
                    filters << "*.bmp" << "*.jpg" << "*.png";
                    dir.setNameFilters(filters);

                    QStringList  string_list = dir.entryList();
                    foreach(QString  var, string_list) {

                        m_vector_detection_thread[i]->m_images_path.push_back(p->m_image_dir + "\\" + var);
                    }
                }
                QTimer* m_qtimer_offline = new QTimer(this);
                connect(m_qtimer_offline, &QTimer::timeout, this, [=]() {
                    m_vector_detection_thread[i]->m_image_index++;
                    if (m_vector_detection_thread[i]->m_images_path.size() > 0)
                    {
                        Mat image_read_file;
                        image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString());
                        if (!image_read_file.empty())
                        {
							HObject hobject_iamge = matToHImage(image_read_file);
                            callback(image_read_file,hobject_iamge, m_vector_detection_thread[i]);
                           /* m_vector_detection_thread[i]->m_camera_index = i;
                            m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);*/
                        }
                    }
                    });
                m_qtimer_offline->start(10);//固定频率读取离线测试图像
            }
            m_vector_camera.push_back(p);
        }
    }
    //处理类和相机类相互关联
    for (int i = 0; i < m_camera_number; i++)
    {
        connect(m_vector_detection_thread[i], &QtThreadProcess::sendShowImage, m_vector_camera[i], &CameraBaseQDialog::showImage);
        
    }
    //login
//      m_qpushbutton_stop_detection->setDisabled(true);
//      m_Login_Dialog = new Login_Dialog(this);
//      m_Login_Dialog->setModal(true);
//      connect(m_Login_Dialog->m_login_button, &QPushButton::clicked, this,&MainWindow::login);
    
    ////tcpsocket
    //{
    //    m_qtcpsocket_unused_used = m_settings_para->value("para/m_qtcpsocket_unused_used", 0).toInt();
    //    m_qtcpsocket_ip = m_settings_para->value("para/m_qtcpsocket_ip", "192.168.2.1").toString();
    //    m_qtcpsocket_port = m_settings_para->value("para/m_qtcpsocket_port", 502).toInt();
    //    if (m_qtcpsocket_unused_used > 0)
    //    {
    //        m_qtcpsocket = new QTcpSocket();
    //        m_qtcpsocket->connectToHost(m_qtcpsocket_ip, m_qtcpsocket_port, QTcpSocket::ReadWrite);
    //        if (!m_qtcpsocket->waitForConnected(100)) {
    //            //QMessageBox::information(nullptr, "TcpSocket", m_qtcpsocket_ip + "" + QString::number(m_qtcpsocket_port));
    //        }
    //        else {
    //            connect(m_qtcpsocket, &QTcpSocket::readyRead, this, [=]() {
    //                QByteArray buffer_read = m_qtcpsocket->readAll();
    //                QString qstring_read = QString(buffer_read);
    //                });
    //        }
    //    }
    //}
    //modbus
   /* {
        m_unuse_use_modbus = m_settings_para->value("para/m_unuse_use_modbus", 0).toInt();
        m_modbus_ip = m_settings_para->value("para/m_modbus_ip", "192.168.2.1").toString();
        m_modbus_port = m_settings_para->value("para/m_modbus_port", 502).toInt();
        if (m_unuse_use_modbus > 0) {
            m_modbus_tcp = modbus_new_tcp(m_modbus_ip.toStdString().c_str(), m_modbus_port);
            if (m_modbus_tcp == nullptr)
                //QMessageBox::information(nullptr, "", "PLC设置参数错误");
            else
                if (modbus_connect(m_modbus_tcp) == -1)
                    //QMessageBox::information(nullptr, "", "PLC连接失败 ");
        }
        m_timer_plc = new QTimer(this);

        connect(m_timer_plc, &QTimer::timeout, this, &MainWindow::timerPLC);
        m_timer_plc->start(100);
    }*/

    if(!m_com.open(m_com_port.toStdString().c_str()))
    {
        QMessageBox::critical(nullptr, "error", m_com_port+ "读取失败");
    }
//    for (int camera_index=0;camera_index<m_camera_number;camera_index++)
//    {
//        m_com.sendInit(camera_index);
//    }
//    short card_no = 1;
//    short ret_sldm = SLDM_Open(m_io_ip.toStdString().c_str(), &card_no, 1500);
//    if( ret_sldm!= 0)
//    {
//        QMessageBox::critical(nullptr, "error", m_io_ip + "IO卡读取失败");
//    }

    QTimer* m_qtimer = new QTimer(this);
    connect(m_qtimer, &QTimer::timeout, this, [=]() {
		for (auto obj : m_vector_show_image)
		{
			obj = true;
		}
    });
    m_qtimer->start(100);
    startDetection();

}

MainWindow::~MainWindow()
{


    logger->warn("程序关闭");
    for (int i = 0; i < m_camera_number; i++)
    {
              if(m_online==1)
                  m_vector_camera[i]->m_camera_interface->camera_end();
              /*for(uint j=0;j<m_vector_detection_thread.size();j++)
                  m_vector_detection_thread[i]->quit();*/
    }
//    m_serial->quit();
}

void MainWindow::clickCamera()
{
    //          if(m_login_privilege <2)
    //          {
    //              //QMessageBox::warning(nullptr, "", "用户登录权限不够");
    //              return;
    //          }
    if (m_vector_detection_thread[0]->m_proess_state == false)
    {
        for (int i = 0; i < m_camera_number; i++)
        {
            m_vector_detection_thread[i]->m_only_show_state = true;
        }
        m_qdialog_camera->show();
    }
    else
    {
        //QMessageBox::warning(nullptr, "Title", "停止检测，再设置参数");
    }
}

void MainWindow::clickPara()
{
    //          if(m_login_privilege <2)
    //          {
    //              //QMessageBox::warning(nullptr, "", "用户登录权限不够");
    //              return;
    //          }
    if (m_vector_detection_thread[0]->m_proess_state == false)
    {
        m_qdialog_detection->show();
        //              m_vector_detection_thread->m_function
        //              m_detection_para_tab_widget->setCurrentIndex(0);

        //              m_detection_para_tab_widget->raise();
    }
    else
    {
        //QMessageBox::warning(nullptr, "", "停止检测，再设置参数");
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    //QMessageBox::information(nullptr, "", "不能从这里退出");
    event->ignore();
}

void MainWindow::closeSoftware()
{
    int ok = QMessageBox::warning(this, ("退出!"), ("你确定退出吗？"), QMessageBox::Yes, QMessageBox::No);
    if (ok == QMessageBox::Yes)
    {
        m_settings_para->setValue("para/geometry", saveGeometry());
        m_settings_para->setValue("para/state", saveState());
        m_settings_para->sync();
		delete m_settings_para;
        dl_3_end();
        qApp->quit();
    }
}

void MainWindow::initImageControl()
{
    m_image_widget = new QWidget();
    setCentralWidget(m_image_widget);
    QGridLayout* qgridlayout = new QGridLayout();
    qgridlayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    qgridlayout->setSpacing(1);
    qgridlayout->setMargin(1);
    m_image_widget->setLayout(qgridlayout);
    int step = (m_camera_number+1)/2;
    for(int i=0;i<m_camera_number;i++)
    {
        ShowQLabel* p = new ShowQLabel(m_image_widget);
       // QPictureBox* p = new QPictureBox(m_image_widget);
        m_vector_show_qlabel.push_back(p);
        qgridlayout->addWidget(p,i/step,i%step,1,1);
    }
}

void MainWindow::initdockDevicesizetable()
{
    m_qdockwidget_devicesizetable = new QDockWidget(("磁盘容量界面"), this);
    m_qdockwidget_devicesizetable->setObjectName("磁盘容量界面");
    m_qdockwidget_devicesizetable->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea|Qt::BottomDockWidgetArea);
    addDockWidget(Qt::RightDockWidgetArea, m_qdockwidget_devicesizetable);
    menuBar()->addMenu(("磁盘容量界面"))->addAction(m_qdockwidget_devicesizetable->toggleViewAction());
    DeviceSizeTable* w = new DeviceSizeTable();
    m_qdockwidget_devicesizetable->setWidget(w);
}

void MainWindow::initdockPannel()
{
    m_qdockwidget_pannel = new QDockWidget(("控制面板界面"), this);
    m_qdockwidget_pannel->setObjectName("控制面板界面");
    m_qdockwidget_pannel->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
    addDockWidget(Qt::LeftDockWidgetArea, m_qdockwidget_pannel);
    menuBar()->addMenu(("控制面板"))->addAction(m_qdockwidget_pannel->toggleViewAction());

    QWidget* qwidget = new QWidget();
    m_qdockwidget_pannel->setWidget(qwidget);

    QVBoxLayout* qvobxlayout = new QVBoxLayout();
    qvobxlayout->setSpacing(30);
    qwidget->setLayout(qvobxlayout);

    m_qpushbutton_start_detection = new QPushButton();
    m_qpushbutton_start_detection->setText("开始检测");
    qvobxlayout->addWidget(m_qpushbutton_start_detection);
    connect(m_qpushbutton_start_detection, &QPushButton::clicked, this, &MainWindow::startDetection);

    m_qpushbutton_stop_detection = new QPushButton();
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setText("停止检测");
    qvobxlayout->addWidget(m_qpushbutton_stop_detection);
    connect(m_qpushbutton_stop_detection, &QPushButton::clicked, this, &MainWindow::stopDetection);

    m_qpushbutton_camera = new QPushButton();
    m_qpushbutton_camera->setText("相机设置");
    qvobxlayout->addWidget(m_qpushbutton_camera);
    connect(m_qpushbutton_camera, &QPushButton::clicked, this, &MainWindow::clickCamera);

    m_qpushbutton_para = new QPushButton();
    m_qpushbutton_para->setText("检测设置");
    qvobxlayout->addWidget(m_qpushbutton_para);
    connect(m_qpushbutton_para, &QPushButton::clicked, this, &MainWindow::clickPara);

    m_qpushbutton_open_image_dir = new QPushButton();
    m_qpushbutton_open_image_dir->setText("打开图像目录");
    qvobxlayout->addWidget(m_qpushbutton_open_image_dir);
    connect(m_qpushbutton_open_image_dir, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl(m_settings_para->value("para/m_save_image_dir", "").toString(), QUrl::TolerantMode));
    });

    m_qpushbutton_open_data_dir = new QPushButton();
    m_qpushbutton_open_data_dir->setText("打开数据目录");
    qvobxlayout->addWidget(m_qpushbutton_open_data_dir);
    connect(m_qpushbutton_open_data_dir, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl(m_save_data_dir, QUrl::TolerantMode));
    });

    m_qpushbutton_open_model_dir = new QPushButton();
    m_qpushbutton_open_model_dir->setText("打开模型目录");
    qvobxlayout->addWidget(m_qpushbutton_open_model_dir);
    connect(m_qpushbutton_open_model_dir, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl(m_type_dir, QUrl::TolerantMode));
    });

    m_qpushbutton_open_help = new QPushButton();
    m_qpushbutton_open_help->setText("打开帮助文档");
    qvobxlayout->addWidget(m_qpushbutton_open_help);
    connect(m_qpushbutton_open_help, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl::fromLocalFile(m_para_dir + "/help.pdf"));
    });

    m_qpushbutton_exit = new QPushButton();
    m_qpushbutton_exit->setText("退出软件");
    qvobxlayout->addWidget(m_qpushbutton_exit);
    connect(m_qpushbutton_exit, &QPushButton::clicked, this, &MainWindow::closeSoftware);

//    qvobxlayout->addStretch();
}

void MainWindow::initMainWindow()
{
    setWindowTitle("工业AI平台检测系统20241216");
    setWindowIcon(QIcon(QCoreApplication::applicationDirPath() + "/picture/logo.svg"));

    initdockPannel();
    initImageControl();
    initdockDevicesizetable();

//    restoreGeometry(m_settings_para->value("para/geometry").toByteArray());
    resize(913,514);
    restoreState(m_settings_para->value("para/state").toByteArray());
}

bool MainWindow::loadPara()
{
    m_exe_directory = QCoreApplication::applicationDirPath();
    m_para_dir = m_exe_directory + "/para";
    QString path;
    path=   m_para_dir + "/para.ini";
    //创建配置文件操作对象
    m_settings_para = new QSettings(path, QSettings::IniFormat);
    m_settings_para->setIniCodec("UTF-8");
    m_save_data_dir=m_settings_para->value("para/m_save_data_dir","").toString();
    m_type_dir =  m_settings_para->value("para/m_type_dir","").toString();
    m_type_dir =  m_exe_directory + "/" + m_type_dir;
    m_type_name =  m_settings_para->value("para/m_type_name","").toString();
    m_user_passward =  m_settings_para->value("para/m_user_passward","").toString();
    m_admin_passeard =  m_settings_para->value("para/m_admin_passeard","").toString();
    m_senior_passeard= m_settings_para->value("para/m_senior_passeard","").toString();
    m_camera_number=m_settings_para->value("para/m_camera_number",1).toInt();
    m_online=m_settings_para->value("para/m_online",-1).toInt();
    m_save_image_dir = m_settings_para->value("para/m_save_image_dir", "").toString();
    m_io_ip = m_settings_para->value("para/m_io_ip","").toString();
    m_com_port = m_settings_para->value("para/m_com_port","").toString();
	m_save_ratio = m_settings_para->value("para/m_save_ratio", 1000).toInt();
//    m_fontsize = m_settings_para->value("para/m_fontsize",9).toInt();
    return true;
}

void MainWindow::login()
{
    if (m_Login_Dialog->m_user_edit->currentText() == "user")
    {
        if (m_Login_Dialog->m_passward_edit->text() == m_user_passward)
        {
            m_login_privilege = 1;
            m_Login_Dialog->m_state_label->setText("user 已登录");
            m_Login_Dialog->hide();
        }
    }
    if (m_Login_Dialog->m_user_edit->currentText() == "admin")
    {
        if (m_Login_Dialog->m_passward_edit->text() == m_admin_passeard)
        {
            m_login_privilege = 2;
            m_Login_Dialog->m_state_label->setText("admin 已登录");
            m_Login_Dialog->hide();
        }
    }
    if (m_Login_Dialog->m_user_edit->currentText() == "senior")
    {
        if (m_Login_Dialog->m_passward_edit->text() == m_senior_passeard)
        {
            m_login_privilege = 3;
            m_Login_Dialog->m_state_label->setText("senior 已登录");
            m_Login_Dialog->hide();
        }
    }
}

void MainWindow::returnMainFrame()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_camera[i]->m_qtimer->stop();
        m_vector_detection_thread[i]->m_only_show_state = false;
    }
    m_qdialog_camera->hide();
    m_qdialog_detection->hide();
}

void MainWindow::saveImage(ShowResult result)
{
    if (result.m_save_right && result.m_detectin_result == true) {
        QString DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name + "/OK/";
        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";
        if(result.m_detection_index%m_save_ratio==0)
            m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_hobject);

//        m_save_image_thread.addImg(path, result.m_image);
    }
    if (result.m_save_wrong && result.m_detectin_result == false) {
        QString DirName = m_save_image_dir +  QDateTime::currentDateTime().toString("/yyyyMMdd/") + result.m_camera_name + "/NG/";
        QDir dir;
        if (!dir.exists(DirName))
        {
            dir.mkpath(DirName);
        }
        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";

        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_hobject);
//     emit m_save_image_thread.addImg(path, result.m_image);
    }
//    if (result.m_save_roi_right && result.m_detectin_result == true) {
//        QString DirName = m_save_image_dir + "/" + result.m_camera_name + "/OKROI/";
//        QDir dir;
//        if (!dir.exists(DirName))
//        {
//            dir.mkpath(DirName);
//        }
//        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";
//        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image(result.m_roi_rect));
//        emit m_save_image_thread.addImg(path, result.m_image);
//        logger->info("save ok roi " + to_string(result.m_detection_index));

//    }
//    if (result.m_save_roi_wrong && result.m_detectin_result == false) {
//        QString DirName = m_save_image_dir + "/" + result.m_camera_name + "/NGROI/";
//        QDir dir;
//        if (!dir.exists(DirName))
//        {
//            dir.mkpath(DirName);
//        }
//        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + ".png";
//         emit m_save_image_thread.addImg(path, result.m_image);
////        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image(result.m_roi_rect));
//        logger->info("save ng roi" + to_string(result.m_detection_index));
//    }
//    if (m_function->m_save_right_label && result.m_detectin_result == true) {
//        QString DirName = m_save_image_dir + "/" + result.m_camera_name + "/OKlabel/";
//        QDir dir;
//        if (!dir.exists(DirName))
//        {
//            dir.mkpath(DirName);
//        }
//        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + "label.png";
//        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);

//    }
//    if (m_function->m_save_wrong_label && result.m_detectin_result == false) {
//        QString DirName = m_save_image_dir + "/" + result.m_camera_name + "/NGlabel/";
//        QDir dir;
//        if (!dir.exists(DirName))
//        {
//            dir.mkpath(DirName);
//        }
//        QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HH_mm_ss_zzz") + "label.png";
//        m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);
//    };
}
void MainWindow::showResult(ShowResult result)
{
    int64 t1 =  cv::getTickCount();
    saveImage(result);

        if(m_vector_show_image[result.m_camera_index]==false)
        {
//               logger->info("no show  image");
            if(result.m_detectin_result==true)
            {
                return;
            }
        }
        else
        {
//               logger->info("show image");
            m_vector_show_image[result.m_camera_index] =false;
        }

//    Mat image = himageToMat(result.hobject);
//    result.m_image_draw = image;
//    result.m_image = image;
//    result.m_frame_rate = pCammerWidget->m_frame_rate;
    //m_function->draw(image, result.m_image_draw);
//    emit pCammerWidget->sendDetectionResult(result);

//    QImage Qtempimage;
//    HObjectToQImage(result.m_hobject,Qtempimage);
    Mat mat_show = himageToMat(result.m_hobject);

    /*double ratio_x =  double(m_vector_show_qlabel[result.m_camera_index]->width()) /  double(mat_show.cols) ;
    double ratio_y =  double(m_vector_show_qlabel[result.m_camera_index]->height()) /  double(mat_show.rows) ;
    double ratio_image = ratio_x < ratio_y ?  ratio_x : ratio_y;

    if(ratio_image >1)
    {
        ratio_image =1;
    }
    else
    {
        cv::resize(mat_show, mat_show, Size(mat_show.cols * ratio_image , mat_show.rows * ratio_image));
    }*/
	cv::resize(mat_show, mat_show, Size(m_vector_show_qlabel[result.m_camera_index]->width(), m_vector_show_qlabel[result.m_camera_index]->height()));

	
    QImage Qtempimage = matToQImage(mat_show);



    QString message_show2;
    if(result.m_detectin_result == true)
    {
        message_show2 = "OK";
    }
    else
    {
        message_show2 = "NG";
    }
////    logger->info(m_vector_camera_name[result.m_camera_index].toStdString() + ":plc and show time" + to_string(m_time_use) + "ms");
    QString message_show  =  result.m_camera_name + QString(":序号%1 检测时间%2ms 帧率%3\n").arg(result.m_detection_index).arg(result.m_time_use).arg(result.m_frame_rate);
	message_show2 += QString("OK数量%1 NG数量%2\n").arg(result.m_ok_count).arg(result.m_ng_count);
	message_show2  +=  result.m_messgae;



    if (!Qtempimage.isNull())
    {
        if(result.m_detectin_result)
            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,QColor(0,255,0));
        else
            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,QColor(255,0,0));
    }
    int64 t2 =  cv::getTickCount();

    double m_time_use = (t2-t1)*1000/getTickFrequency();
//    logger->info( "show time:" + std::to_string(m_time_use ));
}

void MainWindow::startDetection()
{
    string path = (m_exe_directory + "/password").toLocal8Bit().toStdString();
    if(verify(path.c_str())!=true)
    {
        QMessageBox::warning(nullptr, "", "加密文件错误");
        return;
    }

    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = true;
    }
    m_qpushbutton_start_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setDisabled(false);
}

void MainWindow::stopDetection()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = false;
    }
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_start_detection->setDisabled(false);
}

void MainWindow::timerLoadImage()
{
//    //相机离线测试
//    for (int i = 0; i < m_camera_number; i++)
//    {
//        m_vector_detection_thread[i]->m_image_index++;
//        if (m_vector_detection_thread[i]->m_images_path.size() > 0)
//        {
//            Mat image_read_file;
//            image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString());

//            if (!image_read_file.empty())
//            {
//                m_vector_detection_thread[i]->m_camera_index = i;
//                m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);
//            }
//        }
//    }
}

void  MainWindow::timerPLC()
{
    for (int i = 0; i < m_camera_number; i++)
    {

        //        //触发相机拍照
        //        uint16_t plc_trigger_value=0;
        //        if(modbus_read_registers(m_modbus_tcp, 150, 1, &plc_trigger_value)<0)
        //            plc_trigger_value = -1;

        //        logger->info("read m_plc_:" + std::to_string(150) + " " +to_string(plc_trigger_value));
        //        if(1 == plc_trigger_value )
        //        {
        //            m_vector_detection_thread[i]->m_detection_index = 1 ;
        //        }

        //        if(2 == plc_trigger_value )
        //        {
        //            m_vector_detection_thread[i]->m_detection_index = 1 ;
        //        }

        //        if(3 == plc_trigger_value )
        //        {
        //            m_vector_detection_thread[i]->m_detection_index = 1 ;
        //        }

    }

}

